package cn.gok.servlet;

import java.io.InputStream;
import java.net.Socket;
import java.util.Map;

/**
 * @Author: chenfan
 * @Date: 2020/12/6 21:22
 * @Description:
 */
public class RequestProcessor extends Thread{

    private Socket socket;
    private Mapper mapper;

    public RequestProcessor(Socket socket,Mapper mapper){
        this.mapper = mapper;
        this.socket = socket;
    }

    @Override
    public void run() {
        try {
            InputStream inputStream = socket.getInputStream();
            MyRequest request = new MyRequest(inputStream);
            MyResponse response = new MyResponse(socket.getOutputStream());

            /*
             * 根据用户的请求地址， 如果能从servletMap中找到对应的Servlet，则表明要进行的是一个动态资源请求
             * 如果找不到，则说明进行的是静态资源请求
             */
            String hostName = request.getHostName();
            String contextPath = request.getContextPath();
            String url = request.getUrl();

            ServletContext servletContext = mapper.getHostMap().get(hostName).getContexts().get(contextPath);

            HttpServlet httpServlet = servletContext.getServletMap().get(url);

            if (httpServlet == null){
                response.outputHtml( servletContext.getContextAbsolutePath() + "/" + request.getUrl());
            }else{
                httpServlet.service(request, response);
            }
            socket.close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
